<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { Api } from '@/api'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user.js'
import { Document, Packer, Paragraph, TextRun, HeadingLevel, AlignmentType } from 'docx'

const userStore = useUserStore();
const route = useRoute()
const questionnaireId = route.params.id // 获取问卷 ID
const questions = ref([])
const loading = ref(true)
const error = ref(null)
//报告
const dialogVisible = ref(false)
const reportContent = ref('')
const reportData = ref(null)


// 获取问卷题目
const fetchQuestions = async () => {
  try {
    loading.value = true
    const response = await Api.getQuestionnaireQuestions({ questionnaire_id: questionnaireId })
    if (response.data.status === 200) {
      questions.value = response.data.data
    } else {
      throw new Error(response.data.message || '获取问卷题目失败')
    }
  } catch (err) {
    error.value = '加载问卷题目失败，请稍后再试'
    console.error('获取问卷题目失败:', err)
  } finally {
    loading.value = false
  }
}



// 提交问卷答案
const submitAnswers = async () => {
  // 检查所有问题是否都已回答
  const unansweredQuestions = questions.value.filter(q => {
    if (q.question_type === 1 || q.question_type === '单选') {
      return !q.selectedAnswer;
    }
    if (q.question_type === 2 || q.question_type === '多选') {
      return !q.selectedAnswers || q.selectedAnswers.length === 0;
    }
    if (q.question_type === '填空') {
      return !q.answer;
    }
    return false;
  });

  if (unansweredQuestions.length > 0) {
    ElMessage.warning(`还有${unansweredQuestions.length}道题目未完成，请完成所有题目后提交`);
    return;
  }

  const answers = questions.value.map(question => {
    let userAnswer;
    if (question.question_type === 1 || question.question_type === '单选') {
      userAnswer = question.selectedAnswer;
    } else if (question.question_type === 2 || question.question_type === '多选') {
      userAnswer = question.selectedAnswers.join(',');
    } else if (question.question_type === '填空') {
      userAnswer = question.answer;
    }

    // 确保答案不为空
    if (!userAnswer) {
      throw new Error(`题目 ${question.id} 的答案不能为空`);
    }

    return {
      question_id: question.id.toString(),
      user_answer: userAnswer
    };
  });

  try {
    // 显示提交中加载状态
    loading.value = true;

    const response = await Api.submitQuestionnaire({
      questionnaire_id: questionnaireId,
      user_id: userStore.user.id,
      answers
    });

    if (response.data.status === 201) {
      ElMessage.success(response.data.message);

      // 提交成功后生成心理报告
      try {
        const reportResponse = await Api.generatePsychologyReport({
          questionnaire_id: questionnaireId,
          user_id: userStore.user.id
        });

        if (reportResponse.data.status === 200) {
          const data = reportResponse.data.data;
          reportContent.value = data.content || '未能获取报告内容';

          console.log('报告数据:', data);

          // 检查接收到的数据结构
          if (data.range_results) {
            reportData.value = {
              total_score: data.total_score,
              range_results: data.range_results
            };
          } else {
            console.warn('未获取到分段结果数据');
            reportData.value = {
              total_score: data.total_score,
              range_results: {}
            };
          }
        } else {
          reportContent.value = '心理报告生成失败，请稍后重试。';
          reportData.value = null;
          console.error('生成心理报告失败:', reportResponse.data.message);
          ElMessage.error(reportResponse.data.message);
        }
      } catch (err) {
        reportContent.value = '心理报告生成失败，请稍后重试。';
        reportData.value = null;
        console.error('生成心理报告失败:', err);
        ElMessage.error('生成心理报告失败，请稍后再试');
      } finally {
        dialogVisible.value = true;
      }
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (err) {
    ElMessage.error('提交问卷失败，请稍后再试');
    console.error('提交问卷失败:', err);
  } finally {
    loading.value = false;
  }
};

// 导出报告为Word文档
const exportToWord = async () => {
  try {
    // 创建文档
    const doc = new Document({
      sections: [{
        properties: {},
        children: [
          // 标题
          new Paragraph({
            text: reportContent.value.split('\n')[0],
            heading: HeadingLevel.HEADING_1,
            alignment: AlignmentType.CENTER,
          }),

          // 总分
          new Paragraph({
            children: [
              new TextRun({
                text: `总分: ${reportData.value?.total_score}`,
                bold: true,
              }),
            ],
          }),

          // 分隔线
          new Paragraph({
            text: '心理分析详情',
            heading: HeadingLevel.HEADING_2,
            alignment: AlignmentType.CENTER,
          }),

          // 各区域分析
          ...Object.entries(reportData.value?.range_results || {}).map(([rangeName, range]) => [
            new Paragraph({
              children: [
                new TextRun({
                  text: `【${rangeName}】(题目${range.start_question_id}-${range.end_question_id})`,
                  bold: true,
                }),
              ],
            }),
            new Paragraph({
              children: [
                new TextRun({
                  text: `得分: ${range.total_score}`,
                }),
              ],
            }),
            new Paragraph({
              children: [
                new TextRun({
                  text: `状态: ${range.mental_status}`,
                }),
              ],
            }),
            new Paragraph({
              children: [
                new TextRun({
                  text: `建议: ${range.advice}`,
                }),
              ],
            }),
            new Paragraph({ text: '' }), // 空行
          ]).flat(),

          // 完整报告标题
          new Paragraph({
            text: '完整报告',
            heading: HeadingLevel.HEADING_2,
            alignment: AlignmentType.CENTER,
          }),

          // 报告内容
          new Paragraph({
            children: [
              new TextRun({
                text: reportContent.value,
              }),
            ],
          }),
        ],
      }],
    });

    // 生成文档并下载
    const blob = await Packer.toBlob(doc);
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `心理报告_${reportContent.value.split('\n')[0]}.docx`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    ElMessage.success('报告导出成功');
  } catch (error) {
    console.error('导出报告失败:', error);
    ElMessage.error('导出报告失败，请稍后再试');
  }
};




onMounted(() => {
  fetchQuestions()
})
</script>

<template>
  <div class="test-detail">
    <h1>问卷详情</h1>
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <div v-else>
      <div v-for="(question, index) in questions" :key="question.id" class="question-card">
        <h3>题目 {{ index + 1 }}: {{ question.question_text }}</h3>
        <div v-if="question.question_type === 1 || question.question_type === '单选'" class="options">
          <el-radio-group v-model="question.selectedAnswer">
            <el-radio
              v-for="(option, id) in (question.options)"
              :key="id"
              :label="option.option_text"
            >
            {{ option.option_text }}
            </el-radio>
          </el-radio-group>
        </div>
        <div v-else-if="question.question_type === 2 || question.question_type === '多选'" class="options">
          <el-checkbox-group v-model="question.selectedAnswers">
            <el-checkbox
              v-for="(option, idx) in (question.options)"
              :key="idx"
              :label="option.option_text"
            >
            {{ option.option_text }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
        <div v-else-if="question.question_type === '填空'" class="fill-blank">
          <el-input
            v-model="question.answer"
            placeholder="请输入答案"
            clearable
          ></el-input>
        </div>
      </div>
    </div>
    <el-button type="primary" @click="submitAnswers">提交答案</el-button>
    <el-dialog v-model="dialogVisible" title="心理报告结果" width="700px">
      <div class="report-detail" v-if="reportData">
        <div class="report-summary">
          <p><strong>总分:</strong> {{ reportData.total_score }}</p>
        </div>

        <el-divider content-position="center">心理分析详情</el-divider>

        <div v-if="reportData.range_results && Object.keys(reportData.range_results).length > 0">
          <div v-for="(range, rangeName) in reportData.range_results" :key="rangeName" class="range-item">
            <h3>【{{ rangeName }}】(题目{{ range.start_question_id }}-{{ range.end_question_id }})</h3>
            <p><strong>得分:</strong> {{ range.total_score }}</p>
            <p><strong>状态:</strong> {{ range.mental_status }}</p>
            <p><strong>建议:</strong> {{ range.advice }}</p>
          </div>
        </div>

        <el-divider content-position="center">完整报告</el-divider>

        <div class="report-content">
          <pre>{{ reportContent }}</pre>
        </div>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="exportToWord">导出报告</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.test-detail {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.loading,
.error {
  text-align: center;
  font-size: 1.2rem;
  margin: 20px 0;
}

.error {
  color: #ff4444;
}

.question-card {
  background-color: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.question-card h3 {
  margin-bottom: 10px;
}

.options {
  margin-top: 10px;
}

.fill-blank {
  margin-top: 10px;
}

.report-detail {
  padding: 15px;
}

.report-summary {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.report-content {
  background-color: #fff;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 8px;
  max-height: 400px;
  overflow-y: auto;
}

.report-content pre {
  white-space: pre-wrap;
  font-family: Arial, sans-serif;
  line-height: 1.6;
}

.range-item {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 15px;
  border-left: 4px solid #409eff;
}

.range-item h3 {
  margin-top: 0;
  color: #409eff;
  font-size: 16px;
}
</style>